package org.itzixi.netty.utils;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.itzixi.pojo.netty.NettyServerNode;
import org.itzixi.utils.JsonUtils;

import java.net.InetAddress;
import java.nio.charset.StandardCharsets;


@Slf4j
public class ZKUtil {

    public static void registerNettyServer(String nodeName, String ip, int port) throws Exception{
        CuratorFramework client = CuratorConfig.getClient();
        String path = StrUtil.SLASH + nodeName;
        Stat stat = client.checkExists().forPath(path);
        if (stat == null){
            // 为空就创建节点
            client.create().creatingParentsIfNeeded()
                    //创建临时的有序节点
                    .withMode(CreateMode.PERSISTENT)
                    .forPath(path);
        } else {
            log.info("stat:{}", stat);
        }
        NettyServerNode nettyServerNode = new NettyServerNode();
        nettyServerNode.setIp(ip);
        nettyServerNode.setPort(port);
        String nodeJson = JsonUtils.objectToJson(nettyServerNode);
        client.create()
                .withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
                .forPath(path + "/im-", StrUtil.bytes(nodeJson, StandardCharsets.UTF_8));
        log.info("ip为:{}，端口号为：{}的chat-server的服务已经注册到zookeeper", ip, port);

    }

    public static String getLocalIP() throws Exception{
        return InetAddress.getLocalHost().getHostAddress();
    }

    public static void main(String[] args) throws Exception {
        String localIP = getLocalIP();
        System.out.println("localIP = " + localIP);
    }
}
